<?php

// 'content' table
require_once('basemodel.php');
class Content extends BaseModel
{
	var $id = null;
	var $key;
	var $title;
	var $body;
	var $active = 1;
	var $online = 1;
	var $creator_id;
	var $created_at;
	var $updater_id;
	var $updated_at;

	static private $definition;

	static function init()
	{
		self::$definition = new ModelDefinition('content');
		self::$definition->config['restorable'] = true;
		self::$definition->config['timestamps'] = true;
	}

	protected function get_definition()
	{
		return self::$definition;
	}

	function Content()
	{
		parent::BaseModel();
	}

	function get_by_id($id)
	{
		$this->db->select('c.id, c.key, c.title, c.body, c.online, c.creator_id, c.created_at, c.updater_id, c.updated_at, u.firstname as creator_firstname, u.name as creator_name, u2.firstname as updater_firstname, u2.name as updater_name')
			     ->from('content c')
			     ->join('user u', 'c.creator_id = u.id')
			     ->join('user u2', 'c.updater_id = u2.id')
				 ->where('c.id', $id)
				 ->where('c.active', 1);
		$query = $this->db->get();
		return $query->row();
	}

	function plain_get($id)
	{
		$this->db->select('id, title, body, online, created_at, updated_at')
		         ->from('content')
		         ->where('id', $id)
		         ->where('active', 1);
		$query = $this->db->get();
		return $query->row();
	}

	function get_by_key($key)
	{
		$this->db->select('id, key, online, title, body, created_at, updated_at')
			     ->from('content')
			     ->where('key', $key)
			     ->where('active', 1)
				 ->where('online', 1);
		$query = $this->db->get();
		return $query->row();
	}

	/**
	 * @return true si la suppression de la page n'est pas autorisée
	 */
	function is_locked($content)
	{
		return $content->key != '';
	}

   	/**
	 * Liste de tous les contenus
	 */
	function all()
	{
		$this->db->select('c.id, c.key, c.title, c.online, c.created_at, u.name as creator_name, u.firstname as creator_firstname, count(m.id) as count_menu_items')
		         ->from('content c')
		         ->join('user u', 'u.id = c.creator_id')
		         ->join('menu_item m', 'm.content_id = c.id', 'left')
		         ->where('c.active = 1')
		         ->group_by('c.id');
		$query = $this->db->get();
		return $query->result();
	}

	/**
	 * Vérifier et affecter les données utlisateurs
	 * @return liste des erreurs
	 */
	function set_data(&$content, &$data)
	{
		$errors = array();
		if (empty($data['title'])) {
			$errors[] = 'Le titre ne peut pas être vide';
		}
		else {
			$content->title = clean_str($data['title']);
		}
		if (empty($data['body'])) {
			$errors[] = 'Le contenu ne peut pas être vide';
		}
		else {
			$content->body = clean_str_preserve_tags($data['body']);
		}
		$content->online = isset($data['online']);
		return $errors;
	}
}
Content::init();
